package com.tsp_tux.demo.Service;

import com.alibaba.fastjson.JSONObject;
import com.tsp_tux.demo.Dao.*;
import com.tsp_tux.demo.Entity.*;
import com.tsp_tux.demo.Mapper.SubjectMapper;
import com.tsp_tux.demo.Util.easyRespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class SubjectServiceImp implements SubjectService{

    @Autowired
    SubjectRepository subjectRepository;
    @Resource
    UserRepository userRepository;
    @Resource
    Subject_userRepository subject_userRepository;
    @Resource
    ArticleRepository articleRepository;
    @Resource
    Article_User_PraiseRepository article_user_praiseRepository;
    @Resource
    EvalueRepository evalueRepository;
    @Resource
    SubjectMapper subjectMapper;

    @Override
    public RespBean createSubject(String uid, String content, String subName) {
        Subject subject = subjectRepository.findBySubName(subName);

        if (subject == null){
            Subject tempSub = new Subject();
            tempSub.setSubName(subName);
            tempSub.setContent(content);
            tempSub.setUid(uid);

            Date date = new Date(System.currentTimeMillis());
            tempSub.setDate(date);

            subjectRepository.save(tempSub);

            return easyRespBean.ok();
        }

        return easyRespBean.errWithMsg("该专题已存在");
    }

    @Override
    public RespBean getRandom6subjects() {
        return easyRespBean.ok(subjectMapper.getRandom6());
    }

    /**
     * 查看所有的专题页
     * @author 张志豪
     */
    @Override
    public RespBean checkSubjectList(String uid) {
        List<SubjectInfo> subjectInfoList = new ArrayList<>();
        List<Subject> subjectList=new ArrayList<>();
        if (uid.equals("0")) {
            subjectList = subjectRepository.findAll();
        } else {
            User user=userRepository.findByUid(uid);
            if (user.getCategory()==1) {
                subjectList = subjectRepository.findAllByUid(uid);
            }else {
                List<Subject_User> subject_UserList = subject_userRepository.findByUid(uid);
                for (Subject_User su:subject_UserList){
                    subjectList.add(subjectRepository.findBySid(su.getSid()));
                }
            }
        }
        for (Subject sub : subjectList) {
            String founder = userRepository.findByUid(sub.getUid()).getUsername();
            SubjectInfo subjectInfo = new SubjectInfo();
            subjectInfo.setSid(sub.getSid());
            subjectInfo.setSubName(sub.getSubName());
            subjectInfo.setUid(sub.getUid());
            subjectInfo.setFounder(founder);
            subjectInfo.setContent(sub.getContent());
            subjectInfo.setDate(sub.getDate());
            subjectInfo.setParticipateNum(subject_userRepository.countBySid(sub.getSid()));
            subjectInfoList.add(subjectInfo);
        }
        return easyRespBean.ok("查询成功",subjectInfoList);
    }

    /**
     * 查看专题页的内容
     * @author 张志豪
     */
    @Override
    public RespBean checkSubject(int sid, int status,int atype) {
        List<Article> articleList=articleRepository.findAllBySidAndState(sid,1);
        List<ArticleInfo> articleInfoList = new ArrayList<>();
        for (Article article:articleList){
            User user=userRepository.findByUid(article.getUid());
            if (status==1||(status==0&&atype==article.getAtype())) {
                if (user.getCategory()==status){
                    ArticleInfo articleInfo=new ArticleInfo();
                    articleInfo.setAid(article.getAid());
                    articleInfo.setTitle(article.getTitle());
                    articleInfo.setSummary(article.getSummary());
                    articleInfo.setEditTime(article.getEditTime());
                    articleInfo.setAuthor(user.getUsername());
                    articleInfo.setPraiseNumber(article_user_praiseRepository.countByAid(article.getAid()));
                    articleInfo.setMark(getArticleScore(article.getAid()));
                    articleInfoList.add(articleInfo);
                }
            }
        }
        //排序,评分相同则比较时间
        articleInfoList.sort((arg0, arg1) -> {
            float m1 = arg0.getMark();
            float m2 = arg1.getMark();
            if (m1 < m2) {
                return 1;
            } else if (m1 > m2) {
                return -1;
            } else {
                return arg1.getEditTime().compareTo(arg0.getEditTime());
            }
        });
        return easyRespBean.ok("获取专题内容",articleInfoList);
    }

    @Override
    public float getArticleScore(int aid) {
        List<Float> markList=articleRepository.getArticleScoreByAid(aid);
        if (markList.size()==1&&markList.get(0)!=null)
            return markList.get(0);
        else {
            return 0;
        }

    }

    @Transactional
    @Override
    public RespBean deleteSubject(int sid) {
        Subject subject = subjectRepository.findBySid(sid);
        if (subject == null){
            return easyRespBean.errWithMsg("该专题已不存在");
        }else {
            subjectRepository.deleteBySid(sid);
            return easyRespBean.ok();
        }
    }

    @Override
    public RespBean evaluate(int aid, int mark) {
        return null;
    }

    @Override
    public RespBean checkStudent(int sid) {
        List<Subject_User> subject_users = subject_userRepository.findBySid(sid);
        List<Subject_Student> users = new ArrayList<>();
        for (Subject_User temp:subject_users) {
            Subject_Student subject_student = subjectMapper.checkStudent(temp.getUid());
            int count = subjectMapper.queryCount(temp.getUid(), sid);
            subject_student.setA_number(count);
            users.add(subject_student);
        }
        return easyRespBean.ok(users);
    }

    @Override
    public RespBean joinSubject(String uid, int sid) {
        List<Subject_User> subject_users = subject_userRepository.findByUidAndSid(uid, sid);
        if (subject_users.isEmpty()){
            Subject_User temp = new Subject_User();
            temp.setSid(sid);
            temp.setUid(uid);
            subject_userRepository.save(temp);

            return easyRespBean.ok();
        }
        return easyRespBean.errWithMsg("已经加入该专题");
    }

    @Transactional
    @Override
    public RespBean exitSubject(String uid, int sid) {
        List<Subject_User> list = subject_userRepository.findByUidAndSid(uid, sid);
        if (list.isEmpty()){
            return easyRespBean.errWithMsg("该学生并未参与此专题！");
        }else {
            subject_userRepository.deleteByUidAndSid(uid, sid);
            return easyRespBean.ok();
        }
    }

    @Override
    public RespBean inSubject(String uid, int sid) {
        List<Subject_User> list = subject_userRepository.findByUidAndSid(uid, sid);
        JSONObject jsonObject = new JSONObject();
        if (list.isEmpty()){
            jsonObject.put("judge", 0);
        }else {
            jsonObject.put("judge", 1);
        }
        return easyRespBean.ok(jsonObject);
    }

    public RespBean getSubjectDetails(int sid) {
        SubjectInfo subjectInfo=new SubjectInfo();
        Subject subject=subjectRepository.findBySid(sid);
        if (subject==null){
            return easyRespBean.errWithMsg("无此专题");
        }
        subjectInfo.setSubName(subject.getSubName());
        subjectInfo.setFounder(userRepository.findByUid(subject.getUid()).getUsername());
        subjectInfo.setContent(subject.getContent());
        subjectInfo.setDate(subject.getDate());

        return easyRespBean.ok("获取专题内容",subjectInfo);
    }


    /**
     * @param keyword String 关键字
     * @return 搜索专题
     * @author 童一凡
     */
    @Override
    public List<String> searchBlogByKeyword(String keyword){return subjectMapper.searchBlogByKeyword(keyword);}
    public SubjectInfo_1 searchBlogByKeyword2(String sid){return subjectMapper.searchBlogByKeyword2(sid);}

    /**
     * Author 周志伟
     * get[专题参与人数,专题教师文章数,专题资源数,学生知识分享数,学生心得数目]
     * @param sid
     * @return  [专题参与人数,专题教师文章数,专题资源数,学生知识分享数,学生心得数目]
     */
    @Override
    public ArrayList<Integer> getSubjectNumbers(int sid) {
        ArrayList<Integer> statistics = new ArrayList<Integer>();
        statistics.add(subjectMapper.getAttendNum(sid));
        statistics.add(subjectMapper.getTeachArticleNum(sid));
        statistics.add(subjectMapper.getResourceNum(sid));
        statistics.add(subjectMapper.getStudentShareNum(sid));
        statistics.add(subjectMapper.getThinkNum(sid));
        return statistics;
    }

}
